/*=========================================================================

  Library:   CFS

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=========================================================================*/

// Qt includes
#include <QMutexLocker>
#include <QThread>
#include <QHash>

// CFS includes
#include "CFSErrorLogContext.h"
#include "CFSErrorLogStreamMessageHandler.h"
#include "CFSUtils.h"

// STD includes
#include <iostream>
#include <streambuf>
#include <string>

namespace
{

// --------------------------------------------------------------------------
// CFSStreamHandler

//
// See http://lists.trolltech.com/qt-interest/2005-06/thread00166-0.html
//

// --------------------------------------------------------------------------
class CFSStreamHandler : public std::streambuf
{
public:
  CFSStreamHandler(CFSErrorLogStreamMessageHandler* messageHandler,
                   CFSErrorLogLevel::LogLevel logLevel,
                   std::ostream& stream);

  void setEnabled(bool value);

protected:
  virtual int_type overflow(int_type v);
  virtual std::streamsize xsputn(const char *p, std::streamsize n);

private:
  void initBuffer();
  std::string* currentBuffer();

  CFSErrorLogStreamMessageHandler * MessageHandler;
  CFSErrorLogLevel::LogLevel LogLevel;
  CFSErrorLogContext LogContext;

  bool Enabled;

  std::ostream&   Stream;
  std::streambuf* SavedBuffer;
  QHash<Qt::HANDLE, std::string*> StringBuffers;
  QMutex Mutex;
};

// --------------------------------------------------------------------------
// CFSStreamHandler methods

// --------------------------------------------------------------------------
CFSStreamHandler::CFSStreamHandler(CFSErrorLogStreamMessageHandler* messageHandler,
                                   CFSErrorLogLevel::LogLevel logLevel,
                                   std::ostream& stream) :
  MessageHandler(messageHandler), LogLevel(logLevel), Stream(stream)
{
  this->Enabled = false;
}

// --------------------------------------------------------------------------
void CFSStreamHandler::setEnabled(bool value)
{
  if (this->Enabled == value)
    {
    return;
    }

  if (value)
    {
    this->SavedBuffer = this->Stream.rdbuf();
    this->Stream.rdbuf(this);
    }
  else
    {
    // Output anything that is left
//    if (!this->StringBuffer.empty())
//      {
//      Q_ASSERT(this->MessageHandler);
//      this->MessageHandler->handleMessage(this->LogLevel,
//          this->MessageHandler->handlerPrettyName(), this->StringBuffer.c_str());
//      }
    this->Stream.rdbuf(this->SavedBuffer);
    }

  this->Enabled = value;
}

// --------------------------------------------------------------------------
void CFSStreamHandler::initBuffer()
{
  Qt::HANDLE threadId = QThread::currentThreadId();
  if (!this->StringBuffers.contains(threadId))
    {
    this->StringBuffers.insert(threadId, new std::string);
    }
}

// --------------------------------------------------------------------------
std::string* CFSStreamHandler::currentBuffer()
{
  return this->StringBuffers.value(QThread::currentThreadId());
}

// --------------------------------------------------------------------------
std::streambuf::int_type CFSStreamHandler::overflow(std::streambuf::int_type v)
{
  QMutexLocker locker(&this->Mutex);
  this->initBuffer();
  if (v == '\n')
    {
    Q_ASSERT(this->MessageHandler);
    this->MessageHandler->handleMessage(
          CFS::qtHandleToString(QThread::currentThreadId()), this->LogLevel,
          this->MessageHandler->handlerPrettyName(),
          CFSErrorLogContext(this->currentBuffer()->c_str()), this->currentBuffer()->c_str());
    this->currentBuffer()->erase(this->currentBuffer()->begin(), this->currentBuffer()->end());
    }
  else
    {
    *this->currentBuffer() += v;
    }
  return v;
}

// --------------------------------------------------------------------------
std::streamsize CFSStreamHandler::xsputn(const char *p, std::streamsize n)
{
  QMutexLocker locker(&this->Mutex);
  this->initBuffer();
  this->currentBuffer()->append(p, p + n);

  std::string::size_type pos = 0;
  while (pos != std::string::npos)
    {
    pos = this->currentBuffer()->find('\n');
    if (pos != std::string::npos)
      {
      std::string tmp(this->currentBuffer()->begin(), this->currentBuffer()->begin() + pos);
      Q_ASSERT(this->MessageHandler);
      this->MessageHandler->handleMessage(
            CFS::qtHandleToString(QThread::currentThreadId()), this->LogLevel,
            this->MessageHandler->handlerPrettyName(),
            CFSErrorLogContext(tmp.c_str()), tmp.c_str());
      this->currentBuffer()->erase(this->currentBuffer()->begin(), this->currentBuffer()->begin() + pos + 1);
      }
    }
  return n;
}

}

// --------------------------------------------------------------------------
// CFSErrorLogStreamMessageHandlerPrivate

// --------------------------------------------------------------------------
class CFSErrorLogStreamMessageHandlerPrivate
{
public:
  CFSErrorLogStreamMessageHandlerPrivate();
  ~CFSErrorLogStreamMessageHandlerPrivate();

  CFSStreamHandler * CoutStreamHandler;
  CFSStreamHandler * CerrStreamHandler;
};

// --------------------------------------------------------------------------
// CFSErrorLogStreamMessageHandlerPrivate methods

//------------------------------------------------------------------------------
CFSErrorLogStreamMessageHandlerPrivate::CFSErrorLogStreamMessageHandlerPrivate()
{
}

//------------------------------------------------------------------------------
CFSErrorLogStreamMessageHandlerPrivate::~CFSErrorLogStreamMessageHandlerPrivate()
{
  delete this->CoutStreamHandler;
  delete this->CerrStreamHandler;
}

//------------------------------------------------------------------------------
// CFSErrorLogStreamMessageHandler methods

//------------------------------------------------------------------------------
QString CFSErrorLogStreamMessageHandler::HandlerName = QLatin1String("Stream");

// --------------------------------------------------------------------------
CFSErrorLogStreamMessageHandler::CFSErrorLogStreamMessageHandler() :
  Superclass(), d_ptr(new CFSErrorLogStreamMessageHandlerPrivate())
{
  Q_D(CFSErrorLogStreamMessageHandler);
  d->CoutStreamHandler = new CFSStreamHandler(this, CFSErrorLogLevel::Info, std::cout);
  d->CerrStreamHandler = new CFSStreamHandler(this, CFSErrorLogLevel::Critical, std::cerr);
}

// --------------------------------------------------------------------------
CFSErrorLogStreamMessageHandler::~CFSErrorLogStreamMessageHandler()
{
}

// --------------------------------------------------------------------------
QString CFSErrorLogStreamMessageHandler::handlerName()const
{
  return CFSErrorLogStreamMessageHandler::HandlerName;
}

// --------------------------------------------------------------------------
void CFSErrorLogStreamMessageHandler::setEnabledInternal(bool value)
{
  Q_D(CFSErrorLogStreamMessageHandler);
  d->CoutStreamHandler->setEnabled(value);
  d->CerrStreamHandler->setEnabled(value);
}
